package com.xuyiwei.mayi.test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by xuyiwei on 2019/5/6.
 */
class LockDemoThread implements Runnable{
    Lock lock;

    public LockDemoThread(Lock lock ) {
        this.lock = lock;
    }
    @Override
    public void run() {
        try {
            if(lock.tryLock(1100, TimeUnit.SECONDS)){
                System.out.println(Thread.currentThread().getName()+"加锁成功");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else{
                System.out.println(Thread.currentThread().getName()+"加锁失败");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class LockDemo {
    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        for(int i=0;i<100;i++){
            LockDemoThread lockDemo = new LockDemoThread(lock);
            new Thread(lockDemo).start();
        }
    }
}
